// pages/plane/end.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    score: 0,
    money: 0,
    gold: 0,
    end_url: '',
    qrCode: '',
    defeat: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let end_url = ''
    let unit = 0
    if (options.score <= 4000) {
      end_url = 'https://resource.160nurse.com/canvas/healthy/img/plane/cainiao.png'
    } else if (options.score > 4000 && options.score <= 10000) {
      end_url = 'https://resource.160nurse.com/canvas/healthy/img/plane/youxiu.png'
    } else if (options.score > 10000) {
      end_url = 'https://resource.160nurse.com/canvas/healthy/img/plane/jihuang.png'
    }
    wx.getSystemInfo({
      success: function (res) {
        unit = res.screenWidth / 100
      },
    })
    this.setData({
      score: options.score,
      gold: options.gold,
      red: parseFloat(options.red).toFixed(2),
      end_url,
      unit: unit
    })
    this.getData()
    this.getHistory()
    this.getNurtrition()
    this.getQrCode()
  },
  replay () {
    wx.redirectTo({
      url: 'index?link=isredirect',
    })
  },
  // 获取分享二维码
  getQrCode () {
    let that = this
    app.request(app.apiDomain + 'index.php?c=mall&a=goodsQrcode', {
      page: 'plane'
    }, function (res) {
      if (res.data.status == 1) {
        that.setData({
          qrCode: res.data.data.file_path
        })
      }
    }, 'POST')
  },
  getData () {
    let that = this
    app.request(app.apiDomain + 'index.php?c=games&a=plane', {
      point: that.data.score,
      money: that.data.red,
      gold: that.data.gold || 0,
      token: wx.getStorageSync('token')
    }, function (res) {
      if (res.data.status == 1) {
        
      }
    }, 'POST')
  },
  // 查询最高记录
  getHistory() {
    let that = this
    wx.showLoading({
      title: '正在加载',
    })
    app.request(app.apiDomain + 'index.php?c=games&a=planeRecord', {
      point: that.data.score
    }, function (res) {
      wx.hideLoading()
      if (res.data.status == 1) {
        let history = res.data.data
        let defeat = (history.count - history.ranking) > 0 ? parseInt((history.count - history.ranking) / history.count * 100) : 6
        that.setData({
          history,
          defeat
        })
      }
    }, 'POST')
  },
  // 获取推荐水果食材
  getNurtrition() {
    let that = this
    app.request(app.apiDomain + 'index.php?c=foods&a=random_one', {}, function (res) {
      if (res.data.status == 1) {
        let nur = res.data.data
        that.setData({
          nur
        })
      }
    }, 'POST')
  },
  openInvite() {
    let that = this
    that.setData({
      openInvite: true
    })
  },
  closeInvite() {
    let that = this
    that.setData({
      openInvite: false,
      openSave: false
    })
  },
  genePic() {
    let that = this
    that.setData({
      openSave: true
    })
    that.geneHb()
  },
  getGoodsImgPath: function (url) {
    return new Promise((success, fail) => {
      wx.getImageInfo({
        src: url,
        success: res => {
          success(res.path);
        },
        fail: res => {
          fail(res);
        }
      })
    });
  },
  // 生成海报
  geneHb() {
    let that = this
    wx.showLoading({
      title: '正在准备海报',
      icon: 'none'
    })
    let ctx = wx.createCanvasContext('share_pic')
    let url = ''
    let url_text = ''
    if (that.data.score <= 4000) {
      url = 'https://resource.160nurse.com/canvas/healthy/img/plane/cainiao_bg.png'
      url_text = 'https://resource.160nurse.com/canvas/healthy/img/plane/cainiao_text.png'
    } else if (that.data.score <= 10000) {
      url = 'https://resource.160nurse.com/canvas/healthy/img/plane/youxiu_bg.png'
      url_text = 'https://resource.160nurse.com/canvas/healthy/img/plane/youxiu_text.png'
    } else if (that.data.score > 10000) {
      url = 'https://resource.160nurse.com/canvas/healthy/img/plane/jihuang_bg.png'
      url_text = 'https://resource.160nurse.com/canvas/healthy/img/plane/jihuang_text.png'
    } 
    that.getGoodsImgPath(url).then((res) => {
      // ctx.setFillStyle('rgba(255,255,255,0)')
      ctx.save()
      ctx.drawImage(res, 0, 0, 80 * that.data.unit, 134.13 * that.data.unit)
      ctx.restore()
      that.getGoodsImgPath(url_text).then((restext) => {
        ctx.save()
        ctx.drawImage(restext, 4.8 * that.data.unit, 23.46 * that.data.unit, 38.66 * that.data.unit, 6.4 * that.data.unit)
        ctx.restore()
        ctx.setFontSize(3.73 * that.data.unit)
        ctx.fillStyle = '#FFFFFF'
        ctx.fillText('本局得分：', 4.8 * that.data.unit, 39.4 * that.data.unit)
        ctx.setFontSize(5.33 * that.data.unit)
        ctx.fillStyle = '#FFE70F'
        ctx.fillText(that.data.score, 24 * that.data.unit, 39.4 * that.data.unit)
        ctx.setFontSize(3.73 * that.data.unit)
        ctx.fillStyle = '#FFFFFF'
        ctx.fillText('击败了全国', 4.8 * that.data.unit, 46.06 * that.data.unit)
        ctx.setFontSize(5.33 * that.data.unit)
        ctx.fillStyle = '#FFE70F'
        let defeat = (that.data.history.count - that.data.history.ranking + 1) > 0 ? parseInt((that.data.history.count - that.data.history.ranking) / that.data.history.count * 100) : 6
        ctx.fillText(defeat + '%', 24 * that.data.unit, 46.06 * that.data.unit)
        ctx.setFontSize(3.73 * that.data.unit)
        ctx.fillStyle = '#FFFFFF'
        ctx.fillText('的用户', 36 * that.data.unit, 46.06 * that.data.unit)
        console.log(that.data.qrCode)
        that.getGoodsImgPath(that.data.qrCode).then((ress) => {
          ctx.save()
          ctx.drawImage(ress, 26.66 * that.data.unit, 96 * that.data.unit, 26.66 * that.data.unit, 26.66 * that.data.unit)
          ctx.restore()
          ctx.setFontSize(3.2 * that.data.unit)
          ctx.fillStyle = '#666666'
          ctx.fillText('长按识别小程序码立即体验！', 20 * that.data.unit, 128 * that.data.unit)
          ctx.draw(() => {
            console.log('开始')
          })
          wx.hideLoading()
        })
      })
    })
    // ctx.drawImage(url_text, 5.86 * that.data.unit, 37.26 * that.data.unit, 46.66 * that.data.unit, 8.53 * that.data.unit)
  },
  saveImg() {
    let that = this
    if (that.data.isClick) {
      return false
    }
    wx.showToast({
      title: '保存中...',
      icon: 'none'
    })
    let shareImg = ''
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 80 * that.data.unit,
      height: 134.13 * that.data.unit,
      destWidth: 80 * that.data.unit * 2,
      destHeight: 134.13 * that.data.unit * 2,
      canvasId: 'share_pic',
      quality: 1,
      success(res) {
        shareImg = res.tempFilePath
        console.log(res.tempFilePath)
        wx.getSetting({
          success: function (res) {
            that.setData({
              isClick: true
            })
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function (resp) {
                // let imgUrl = shareImg
                // console.log(imgUrl)
                // wx.downloadFile({
                //   url: imgUrl,
                //   success: function (res) {
                //     wx.hideLoading()
                //     // console.log(respon);
                wx.saveImageToPhotosAlbum({
                  filePath: shareImg,
                  success: function (response) {
                    console.log(response)
                    that.setData({
                      isClick: false,
                      openInvite: false
                    })
                    wx.hideLoading()
                    wx.showToast({
                      title: '保存成功',
                      icon: 'success'
                    })
                  }
                })
                //   }
                // })
              },
              fail: function () {
                wx.hideLoading()
                that.setData({
                  isClick: false
                })

              },
              complete: function (res) {
                // wx.hideLoading()
                console.log(res)
                if (res.errMsg.indexOf('authorize:fail') !== -1) {
                  wx.showToast({
                    title: '您未打开授权，请前往个人中心授权管理开启授权',
                    icon: 'none'
                  })
                }
                that.setData({
                  isClick: false
                })
              }
            })
          }
        })
      }
    })
  },
  show () {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.SystemInfo(this)
  },
  return_index() {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  return_act() {
    wx.redirectTo({
      url: 'index?link=isredirect',
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    let nickName = '';
    let userId = 0;
    try {
      nickName = wx.getStorageSync('nickname');
      userId = wx.getStorageSync('user_id');
    } catch (e) { }

    return {
      path: "/pages/plane/index?user_id=" + userId,
      title: '打水果，拼手速，本局得分' + that.data.score + '，击败了' + that.data.defeat + '%的玩家',
      imageUrl: app.resourceDomain + 'canvas/healthy/img/plane/comon.png'
    }
  }
})